<template>
  <div class="box">
    <el-row>
      <el-col :span="24">
        <div class="header">
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="100px"
            class="flex-start"
          >
            <el-form-item label="所属网点" prop="networkName">
              <el-select
                v-model="form.networkName"
                placeholder="请选择所属网点"
                style="width: 275px"
              >
                <el-option
                  v-for="item in networkList"
                  :key="item.value"
                  :label="item.networkName"
                  :value="item.networkName"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search">查询</el-button>
              <el-button @click="mxClear">重置</el-button>
              <el-button icon="el-icon-upload2" @click="exportData"
                >导出</el-button
              >
              <el-button plain icon="el-icon-s-custom" @click="addParent"
                >添加父客户</el-button
              >
              <el-button plain icon="el-icon-s-custom" @click="addSon"
                >添加子客户</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <div v-if="tableData !== null">
          <el-table
            v-loading="loading"
            :header-cell-style="{ 'background-color': '#F5F7FA' }"
            :data="tableData"
            style="width: 100%; margin-bottom: 20px"
            row-key="id"
            border
            :tree-props="{ children: 'clientRelations' }"
            height="600px"
          >
            <el-table-column
              prop="clientCode"
              label="客户编码"
              header-align="center"
              align="center"
            />
            <el-table-column
              prop="clientName"
              label="客户名称"
              header-align="center"
              align="center"
            />
            <el-table-column
              prop="clientMode"
              label="客户模式"
              header-align="center"
              align="center"
            />
            <el-table-column
              prop="networkName"
              label="网点名称"
              header-align="center"
              align="center"
            />
            <el-table-column
              prop="level"
              label="级别"
              header-align="center"
              align="center"
            />
            <el-table-column label="操作" header-align="center" align="center">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="handleClick(scope.row)"
                  >修改</el-button
                >
                <el-button type="text" size="small" @click="remove(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- <div v-if="tableData == null">
          <empty />
        </div> -->
      </el-col>
    </el-row>
    <!-- <div
      class="block"
      style="display: flex; justify-content: flex-end"
    >
      <el-pagination
        :current-page="form.pageDate.pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="form.pageDate.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div> -->
    <el-dialog title="父客户" :visible.sync="parentClient" width="30%">
      <el-form :model="parentForm">
        <el-form-item label="所属网点">
          <el-select
            v-model="parentForm.networkName"
            placeholder="请选择所属网点"
            style="width: 275px"
            @change="changeParent(networkList)"
          >
            <el-option
              v-for="item in networkList"
              :key="item.value"
              :label="item.networkName"
              :value="item.networkName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户编码">
          <el-input
            v-model="parentForm.clientCode"
            placeholder="请输入客户编码"
            style="width: 275px"
          />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input
            v-model="parentForm.clientName"
            placeholder="请输入客户名称"
            style="width: 275px"
          />
        </el-form-item>
        <el-form-item label="客户模式" prop="clientMode">
          <el-select v-model="parentForm.clientMode" placeholder="请选择">
            <el-option
              v-for="item in khmode"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="parentClient = false">取 消</el-button>
        <el-button type="primary" @click="addParentForm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="子客户" :visible.sync="sonClient" width="30%">
      <el-form :model="sonForm">
        <el-form-item label="父级客户">
          <el-select
            v-model="sonForm.parentId"
            placeholder="请选择父级客户"
            style="width: 275px"
          >
            <el-option
              v-for="item in parentClientList"
              :key="item.value"
              :label="item.clientName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户编码">
          <el-input
            v-model="sonForm.clientCode"
            placeholder="请输入客户编码"
            style="width: 275px"
          />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input
            v-model="sonForm.clientName"
            placeholder="请输入客户名称"
            style="width: 275px"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sonClient = false">取 消</el-button>
        <el-button type="primary" @click="addSonForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改" :visible.sync="alter" width="30%">
      <el-form ref="xgform" :rules="xgrules" :model="updatesj">
        <el-form-item label="客户编码" prop="clientCode">
          <el-input
            v-model="updatesj.clientCode"
            placeholder="请输入客户编码"
            style="width: 275px"
          />
        </el-form-item>
        <el-form-item label="客户名称" prop="clientName">
          <el-input
            v-model="updatesj.clientName"
            placeholder="请输入客户名称"
            style="width: 275px"
          />
        </el-form-item>
        <el-form-item label="客户模式" prop="clientMode">
          <el-select v-model="updatesj.clientMode" placeholder="请选择">
            <el-option
              v-for="item in khmode"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属网点" prop="networkName">
          <el-select
            v-model="updatesj.networkName"
            placeholder="请选择所属网点"
            style="width: 275px"
          >
            <el-option
              v-for="item in networkList"
              :key="item.value"
              :label="item.networkName"
              :value="item.networkName"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="alter = false">取 消</el-button>
        <el-button type="primary" @click="alterupdatesj">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOutletsList,
  // getSubjectFirstList,
  // getSubjectList
  // subjectSearch,
  // addSubject
} from "@/api/dashboard";
import {
  useSetting,
  addParentClient,
  addSonClient,
  getParentClient,
  khupdate,
  khdelete,
} from "@/api/user";
// import { GetclientRelation } from '@/api/apifile/Networkfinance'
// import empty from '@/components/menuComponent/empty.vue'
// import networkSelect from '@/components/menuComponent/NetworkSelect.vue'
import { exportDatakhpz } from "@/api/home";

export default {
  // components: { empty, networkSelect },

  data() {
    return {
      xgrules: {
        clientName: [
          { required: true, message: "请输入客户名称", trigger: "blur" },
        ],
        clientMode: [
          { required: true, message: "请选择客户模式", trigger: "change" },
        ],
        clientCode: [
          { required: true, message: "请输入客户编码", trigger: "change" },
        ],
        networkName: [
          { required: true, message: "请选择网点名称", trigger: "change" },
        ],
      },
      khmode: [
        { value: 1, label: "直营模式" },
        { value: 2, label: " 承包区模式" },
      ],
      form: {
        networkName: "辽宁盘锦公司",
        pageDate: {
          pageNum: 1,
          pageSize: 10,
        },
      },
      formLabelWidth: "120px",
      parentForm: {
        networkName: "",
        networkCode: "",
        clientCode: "",
        clientName: "",
        clientMode: "",
      },
      sonForm: {
        parentId: "",
        clientCode: "",
        clientName: "",
      },
      updatesj: {
        clientCode: "",
        clientMode: "",
        clientName: "",
        networkName: "",
      },
      parentClientList: null,
      // 网点列表
      networkList: null,
      pages: {
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      loading: false,
      parentClient: false,
      sonClient: false,
      alter: false,
      currentPage4: 4,
      tableData: [],
      rules: {
        networkName: [
          { required: true, message: "请选择网点名称", trigger: "blur" },
        ],
      },
      text: "",
    };
  },
  mounted() {
    // this.getList();
    this.getOutLet();
    this.getUserInfo();
    // this.getSubjectFirst();
  },
  methods: {
    // 删除按钮
    remove(row) {
      // row.level
      if (row.clientRelations === null) {
        this.text = "确定删除吗？";
      } else {
        this.text = "父客户下存在子客户，是否继续删除？";
      }
      console.log(row);
      this.$confirm(this.text, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await khdelete({ id: row.id });
          this.search();
          this.$message({
            type: "success",
            message: `${res.data}`,
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 修改按钮
    handleClick(row) {
      // console.log(row)
      const updatesj1 = row;
      this.updatesj = { ...updatesj1 };
      this.alter = true;
    },
    // 确定修改
    async alterupdatesj() {
      this.$refs.xgform.validate(async (valid) => {
        if (valid) {
          this.alter = false;
          const res = await khupdate(this.updatesj);
          if (res.code === 200) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.getUserInfo();
          } else {
            this.$message({
              message: "修改失败",
              type: "error",
            });
          }
        }
      });
    },
    // 获取父客户列表
    getParentClient() {
      getParentClient().then((res) => {
        if (res.code === 200) {
          this.parentClientList = res.data;
        }
      });
    },
    // 获取子客户列表)
    changeParent(data) {
      const arr = data.filter(
        (el) => el.networkName === this.parentForm.networkName
      );
      this.parentForm.networkCode = arr[0].networkCode;
    },
    getParentClientList() {
      getParentClient().then((res) => {
        if (res.code === 200) {
          this.parentClientList = res.data;
        }
      });
    },
    async getUserInfo() {
      this.loading = true;
      const res = await useSetting(this.form);
      if (res.code === 200) {
        this.tableData = res.data;
      }
      this.loading = false;
    },
    exportData() {
      this.$refs.form.validate((res) => {
        if (res) {
          this.$notify.info({
            title: "开始下载,请稍后...",
          });
          exportDatakhpz().then((res) => {
            const url = window.URL.createObjectURL(new Blob([res]), {
              type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            });
            const link = document.createElement("a");
            link.href = url;
            link.setAttribute("download", "客户配置列表.xlsx"); // 设置下载的文件名
            document.body.appendChild(link);
            link.click();
            link.parentNode.removeChild(link);
          });
          this.$notify({
            title: "下载成功",
            type: "success",
          });
        }
      });
    },
    bg(value) {
      // console.log(value)
      if (value === 2) {
        this.isart = true;
      } else {
        this.isart = false;
      }
    },
    handleSizeChange(val) {
      this.form.pageDate.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) {
      this.form.pageDate.pageNum = val;
      this.init();
    },
    mxClear() {
      this.form.networkName = "";
    },
    search() {
      this.$refs.form.validate((res) => {
        if (res) {
          this.init();
        }
      });
    },
    init() {
      this.loading = true;
      useSetting(this.form).then((res) => {
        if (res.code === 200) {
          this.tableData = res.data;
        } else {
          this.tableData = [];
        }

        this.loading = false;
        // this.tableData = res.data
        // this.total = res.data.list.total
        // this.form.pageDate.pageNum = res.data.list.current
      });
    },
    mxDateChange(value) {
      this.form.startTime = value[0];
      this.form.endTime = value[1];
    },
    // ------------------------------------
    // 获取网点列表
    getOutLet() {
      getOutletsList().then((res) => {
        if (res.code === 200) {
          this.networkList = res.data;
        }
      });
    },
    // 打开配置弹窗
    addParent() {
      Object.keys(this.parentForm).forEach((key) => {
        this.parentForm[key] = "";
      });
      this.parentClient = true;
    },
    addSon() {
      Object.keys(this.sonForm).forEach((key) => {
        this.sonForm[key] = "";
      });
      this.getParentClientList();
      this.sonClient = true;
    },
    async addParentForm() {
      if (
        this.parentForm.networkName === "" ||
        this.parentForm.clientName === "" ||
        this.parentForm.clientCode === "" ||
        this.parentForm.clientMode === ""
      ) {
        this.$message("请补全选项");
      } else {
        const res = await addParentClient(this.parentForm);
        if (res.code === 200) {
          this.$message({
            message: `${res.data}`,
            type: "success",
          });
          this.parentClient = false;
          this.getUserInfo();
        }
      }
    },
    async addSonForm() {
      if (
        this.sonForm.networkName === "" ||
        this.sonForm.clientName === "" ||
        this.sonForm.clientCode === ""
      ) {
        this.$message("请补全选项");
      } else {
        const res = await addSonClient(this.sonForm);
        if (res.code === 200) {
          this.$message({
            message: `${res.data}`,
            type: "success",
          });
          this.sonClient = false;
          this.getUserInfo();
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  padding: 20px;
}

.flex {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.flex-start {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.flex-bettom {
  display: flex;
  justify-content: space-between;
}

.header {
  padding-bottom: 20px;
  border-bottom: 1px solid #ccc;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
